package com.wy2.eclipse.tool.lib.neoodb;

import java.io.File;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SessionManager {
    
    private static Logger logger=LoggerFactory.getLogger(SessionManager.class);

	private static SessionFactory sessionFactory=null;
	
	public static void initSessionFactory(File dbDirectory) {
		sessionFactory=new SessionFactory(dbDirectory);
	}
	
	//private static ConcurrentMap<String, Session>
	
	private static ThreadLocal<ConcurrentMap<String, Session>> localSession=new ThreadLocal<>();
	
	public static Session getCurrent(String dbName) {
	    ConcurrentMap<String, Session> sessions=localSession.get();
	    if(sessions==null) {
	        sessions=new ConcurrentHashMap<>();
	        localSession.set(sessions);
	    }
	    Session session=sessions.get(dbName);
	    if(session==null) {
	        session=sessionFactory.createSession(dbName);
	        sessions.put(dbName, session);
	    }
	    return session;
	}
	
	public static void closeSession(String dbName) {
	    ConcurrentMap<String, Session> sessions=localSession.get();
	    Session session=sessions.get(dbName);
	    sessions.remove(dbName);
	    localSession.set(null);
	    if(session!=null && session.getOdb()!=null && !session.getOdb().isClosed()) {
	        try {
                session.close();
            } catch (Exception e) {
                logger.error("关闭连接失败,dbName:"+dbName, e);
            }
	    }
	}
	
	public static void closeAllSession() {
	    ConcurrentMap<String, Session> sessions=localSession.get();
	    if(sessions==null) {
	        return;
	    }
	    
	    for (Entry<String, Session> kv : sessions.entrySet()) {
            try {
                kv.getValue().close();
            } catch (Exception e) {
                logger.error("关闭连接失败,dbName:"+kv.getKey(), e);
            }
        }
	    
	}
}
